package pers.dawnyang.modular.system.controller;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.dawnyang.common.core.domain.Result;
import pers.dawnyang.common.core.domain.entity.SysDictType;
import pers.dawnyang.common.core.util.ResultUtil;
import pers.dawnyang.config.cache.DictCacheService;
import pers.dawnyang.config.cache.DictData;
import pers.dawnyang.modular.system.domain.response.common.DictValue;
import pers.dawnyang.modular.system.service.DictTypeService;
import pers.dawnyang.modular.system.service.DictValueService;

/***
 * 公共请求处理**
 * 
 * @author dawn yang
 * @date 2021/05/08
 */
@Controller
@RequestMapping("/sys/common")
public class CommonController {

  @Autowired
  private DictTypeService dictTypeService;

  @Autowired
  private DictValueService dictValueService;

  @Autowired
  private DictCacheService dictCacheService;



  /**
   * 通过字典编码获取值
   *
   * @param typeCode
   * @return
   */
  @GetMapping("/getDictValueByCode")
  @ResponseBody
  public Result<List<DictValue>> getDictValueByCode(String typeCode) {
    List<DictValue> list = dictCacheService.getDictValueList(typeCode);
    if (null == list || list.size() == 0) {
      list = dictValueService.getDictValueByCode(typeCode);
      dictCacheService.setDictValueList(typeCode, list);
    }
    return ResultUtil.success(list);
  }

  /**
   * 前端刷新页面时，获取所有字典
   *
   * @return
   */
  @GetMapping("/dict")
  @ResponseBody
  public Result<List<DictData>> getDictData() {
    List<DictData> dictDataList = new ArrayList<>();
    List<SysDictType> typeListCache = dictCacheService.getTypeListCache();
    if (null == typeListCache || typeListCache.size() == 0) {
      dictTypeService.initDictCache();
      typeListCache = dictCacheService.getTypeListCache();
    }
    for (SysDictType sysDictType : typeListCache) {
      DictData dictData = new DictData();
      List<DictValue> dictValueList = dictCacheService.getDictValueList(sysDictType.getTypeCode());
      dictData.setValueList(dictValueList);
      dictData.setTypeCode(sysDictType.getTypeCode());
      dictDataList.add(dictData);
    }
    return ResultUtil.success(dictDataList);
  }

}
